
import { PageContainer } from "@ant-design/pro-components"
import { Card, Button, Col, Form, Input, Row, Select, Upload, message, Table, Flex, InputNumber } from 'antd';
import { useState, useEffect, } from "react"
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import { PlusOutlined } from '@ant-design/icons';
import "./AddGoods.css"
import { getCategoryList, getSysAttrList, productAdd } from "@/services/goods/index"
import Spec from "@/components/Spec"
import { createGoods } from "@/utils/utils"
import { history } from "@umijs/max";
import { getGoodsDetail } from "./index"
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
import PriceType from "./PriceType"
import ShippingCity from "./ShippingCity"
import DatePick from "./DatePick"


function Add() {

    //搜索的
    const [form] = Form.useForm();

    const [editorState, setEditorState] = useState(BraftEditor.createEditorState(null));
    const [categoryList, setCategoryList] = useState<GOODSAPI.CateDate[] | undefined>([]);
    const [categoryAttrList, setCategoryAttrList] = useState<GOODSAPI.Attr[] | undefined>([])

    /* -------------- */

    //用户存储属性组件传递出来的数据
    const [checkedAttrs, setCheckedAttrs] = useState<any[]>([])

    //拼装的表头数据
    const [columnsProps, setColumnsProps] = useState<any[]>([]);
    //拼装的表数据
    const [dataSourceProps, setDataSourceProps] = useState<any[]>([]);

    /* --------------- */

    const [imgs, setImgs] = useState<string[]>([]);
    //React组件传值

    // useEffect(() => {
    //     ; (async () => {
    //         let { data } = await getCategoryList()
    //         if (data) {
    //             setCategoryList(data.list)
    //         }


    //     })()
    // }, [])


    const formItemLayout = {
        labelCol: {
            xs: { span: 20 },
            sm: { span: 4 },
        },
        wrapperCol: {
            xs: { span: 20 },
            sm: { span: 10 },
        },
    };

    const tailFormItemLayout = {
        wrapperCol: {
            xs: {
                span: 24,
                offset: 0,
            },
            sm: {
                span: 18
            },
        },
    };

    //提交商品
    const onFinish = async (data: any) => {


        let goodsParams = dataSourceProps.map((item) => {

            let tempItem = { ...item };
            //删多余属性
            delete tempItem.key;

            let specAttr = [];
            for (let key in tempItem) {
                specAttr.push({
                    name: key,
                    val: tempItem[key]
                })
            }
            // {"颜色":"红",CPU:"i5"} [{name: "内存", val: "4g"},{name:"cpu",val:I5} ]
            return {
                categoryId: data.categoryId,
                pCategoryId: 0,
                name: data.name,
                desc: data.desc,
                price: data.price,
                detail: data.detail.toHTML(),
                imgs: imgs,
                specAttr
            }
        })



        let allGoods = goodsParams.map((item) => {
            return new Promise((resolve, reject) => {
                productAdd(item).then((res) => {
                    resolve(res)
                })
            })
        })

        let res = await Promise.all(allGoods);

        message.success("添加成功!");

        setTimeout(() => {
            history.push("/goods/list")
        }, 500)

    }
    // // 获取富文本
    // const handleBraftEditor = (editorState) => {
    //     console.log(editorState.toHTML());
    // }

    //获取属性列表
    const handleCategory = async (id: any) => {
        let { data } = await getSysAttrList()
        setCategoryAttrList(data)
    }

    //处理并接受用户选择的属性的属性值
    const handleCheckedAttrList = (_id: string, name: string, category_id: string, value: any[]) => {

        //在外部需要有一个数组，来装用户选择的属性 和 属性值 

        // checkedAttrs

        let chooseAttr = checkedAttrs.find((item) => item._id === _id)
        if (!chooseAttr) {
            checkedAttrs.push({
                _id,
                value, //就是选择了那个属性的属性值 是一个数组
                name,
                category_id
            })
        } else {
            //如果在数组里面找到了 就直接修改就好了 
            chooseAttr.value = value
        }
        setCheckedAttrs([...checkedAttrs]);

        //下一步 是不是要点击生成，生成一个列表 
    }

    //生成sku
    const handleCreateSKU = () => {
        //判断用于是不是选择好了 属性
        if (categoryAttrList?.length == checkedAttrs.length) {

            //开始拼装数据

            //获取凭证数据的具体值
            let tempProps = checkedAttrs.map((item) => item.value)
            //拼装数据
            let skuProps = createGoods(tempProps);

            // 开始拼装table列表
            // 拼装表头

            let checkedKeys = checkedAttrs.map((item) => item.name);

            let columnsPropsTemp = [];
            for (let i = 0; i < checkedKeys.length; i++) {
                columnsPropsTemp.push(
                    {
                        title: checkedKeys[i],
                        dataIndex: checkedKeys[i],
                        key: checkedKeys[i]
                    }
                )
            }
            columnsPropsTemp.push({
                title: "价格",
                dataIndex: "price", //我们等下拼数据的时候 也要这个key
                key: "price",
                render: (_: any, record: any) => {
                    return <Input onChange={(e) => { record.price = e.target.value.trim(); setDataSourceProps([...dataSourceProps]) }}></Input>
                }
            }, {
                title: "库存",
                dataIndex: "inventory", //我们等下拼数据的时候 也要这个key
                key: "inventory",
                render: (_: any, record: any) => {
                    return <Input onChange={(e) => { record.inventory = e.target.value.trim(); setDataSourceProps([...dataSourceProps]) }}></Input>
                }
            }, {
                title: "操作",
                dataIndex: "edit", //我们等下拼数据的时候 也要这个key
                key: "edit",
                render: (_: any, record: any) => <Button size="small">删除</Button>
            })
            setColumnsProps(columnsPropsTemp);
            //拼数据

            /* 
              这是要拼装的table的数据对象{ "颜色":"xx","cpu":"xx","key":""} 
              
              还有有一个数组来装有多少条数据 [ ] dataSourceProps 

             
            */

            // 要确定有多少条数据？

            for (let i = 0; i < skuProps.length; i++) {

                let tempDataObj: any = {}
                for (let j = 0; j < checkedKeys.length; j++) {
                    tempDataObj[checkedKeys[j]] = skuProps[i][j]
                }

                dataSourceProps.push({
                    ...tempDataObj,
                    price: "",
                    inventory: "",
                    key: i + 1
                })
            }

            //再更新视图
            setDataSourceProps([...dataSourceProps])

        } else {
            message.warning("属性选择错误！");
        }

    }

    // let handleImgUpload = ({ file:any }) => {
    //     if (file.response) {
    //         setImgs([...imgs, file.response.data.name])
    //     }
    // }
    //页面挂在请求商品数据
    useEffect(() => {
        getGoodsDetail
    })



    return (
        <PageContainer>

            <Card>
                <Flex gap="small" wrap>
                    <Button style={{ height: '31.99px ', width: '63.84px' }} onClick={() => { window.location.href = './Goods/Details'; }} type="primary" className="out-button" >返回</Button>

                </Flex>
                <Form
                    {...formItemLayout}
                    form={form}
                    name="register"
                    onFinish={onFinish}
                    initialValues={{

                    }}
                    size="large"
                    scrollToFirstError
                >
                    <h2> </h2>

                    <h2>基本信息</h2>
                    <Form.Item
                        name="name"
                        label="商品名称"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品名称',
                            },
                        ]}
                    >
                        <Input placeholder="请输入商品名称" />
                    </Form.Item>

                    <Form.Item
                        name="desc"
                        label="商品文字描述"
                        rules={[{ required: true, message: '请输入商品描述' }]}
                    >
                        <Input.TextArea maxLength={1000} placeholder="请输入商品描述" />
                    </Form.Item>

                    <Form.Item
                        name="price"
                        label="商品价格"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品价格',
                            },
                        ]}
                        hasFeedback
                    >

                        <Input type="number" placeholder="请输入商品价格" addonAfter="元" />
                    </Form.Item>
                    <Form.Item
                        name="categoryId"
                        label="商品类型"
                        rules={[{ required: true, message: 'Please select gender!' }]}
                    >
                        <Select placeholder="请选择商品类型" onChange={handleCategory}>
                            {
                                categoryList?.map((item) => <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>)
                            }

                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="categoryId"
                        label="商品分类"
                        rules={[{ required: true, message: 'Please select gender!' }]}
                    >
                        <Select placeholder="请选择商品分类" onChange={handleCategory}>
                            {
                                categoryList?.map((item) => <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>)
                            }

                        </Select>
                    </Form.Item>



                    <Form.Item label="商品头图" valuePropName="fileList">
                        <Upload headers={{ Authorization: `Bearer ${localStorage.token}` }} /*onChange={ handleImgUpload }*/  //这里为了能够先做页面，注释掉了
                            name="image" action="/api/manage/img/upload" listType="picture-card">
                            <div>
                                <PlusOutlined />
                                <div style={{ marginTop: 8 }}>点击上传</div>
                            </div>
                        </Upload>
                    </Form.Item>




                    <Form.Item label="商品详情" name="detail" {...tailFormItemLayout}>

                        <BraftEditor className="my-editor" value={editorState} />

                    </Form.Item>
                    <h2>服务条款</h2>
                    <Form.Item
                        name="vendor"
                        label="供应商名称"
                        rules={[
                            {
                                required: true,
                                message: '请输入供应商名称',
                            },
                        ]}
                    >
                        <Input placeholder="请输入供应商名称" />
                    </Form.Item>
                    <Form.Item
                        name="vendorContact"
                        label="供应商联系方式"
                        rules={[
                            {
                                required: true,
                                message: '请输入供应商联系方式',
                            },
                        ]}
                    >
                        <Input placeholder="请输入供应商联系方式" />
                    </Form.Item>
                    <Form.Item
                        name="ServiceGuarantee"
                        label="服务保障"
                        rules={[{ required: true, message: '请输入服务保障' }]}
                    >

                        <Input.TextArea maxLength={1000} placeholder="请输入服务保障" />
                    </Form.Item>
                    <Form.Item
                        name="PriceType"
                        label="黄金会员价格类型"
                        rules={[{ required: true, message: '请输入服务保障' }]}
                    >
                        {/* 黄金会员价格类型 */}
                        <PriceType />


                    </Form.Item>

                    <h2>快递</h2>

                    <Form.Item
                        name="UnShippingCity"
                        label="不发货地区"
                        rules={[{ required: true, message: '请输入发货城市' }]}
                    >
                        {/* 发货城市 */}
                        <ShippingCity />

                    </Form.Item>
                    <h2>兑换限制</h2>
                    <Form.Item
                        name="Limit"
                        label="兑换上限"
                        rules={[
                            {
                                required: true,
                                message: '请输入兑换上限',
                            },
                        ]}
                    >
                        <InputNumber min={0} style={{ width: '40%' }} />
                    </Form.Item>
                    <h2>投放</h2>
                    <Form.Item name="UpTime" label="上线时间" rules={[{ required: true, message: '请选择上线时间' }]}>
                        <DatePick />
                    </Form.Item>
                    <Form.Item name="DownTime" label="下线时间" rules={[{ required: true, message: '请选择上线时间' }]}>
                        <DatePick />
                    </Form.Item>
                    <Form.Item name="ShippingCity" label="投放城市" rules={[{ required: true, message: '请选择投放城市' }]}>
                        <ShippingCity />
                    </Form.Item>



                    <Form.Item wrapperCol={{ sm: { span: 18, offset: 4 } }}>

                        <Button style={{ marginLeft: 10, marginRight: 10 }} type="primary" htmlType="submit" >
                            提交
                        </Button>
                        <Button style={{ marginLeft: 10, marginRight: 10 }} type="primary" htmlType="submit">
                            重置
                        </Button>
                        <Button style={{ marginLeft: 10, marginRight: 10 }} type="primary" htmlType="submit">
                            暂存
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </PageContainer >
    );
}

export default Add;